var express = require('express');
var jwt = require('jsonwebtoken');
var CONFIG = require('./../config');
var usersDao = require('./../dao/users');
var uploadPicHelper = require('../util/uploadPicHelper');
var QcloudSms = require("qcloudsms_js");
require('./../util/common');
require('./../util/bootloader');
var router = express.Router();

/**
 * @api {POST} /users/regist 用户注册
 * @apiDescription 用户注册接口，注册成功赠送300积分，邀请其他人注册可赠送15积分，积分可下载资源使用
 * @apiName userRegist
 * @apiParam {String} account 用户手机号(必填)
 * @apiParam {String} password 用户密码(必填)
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} username 用户名(必填)
 * @apiParam {String} comment 用户简介(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiParamExample {json} 请求示例:
 * {
 *      "account": "18506921111",
 *      "password": "zxw68824",
 *      "app_sid": "NYL",
 *      "username": "逆月翎",
 *      "comment": "NodeJs后端开发工程师",
 *      "time": "1560505477541",
 *      "sign": "416057ec384b744f4536fddcab24746f"
 * }
 * @apiSampleRequest http://www.niyueling.cn/users/regist
 * @apiSuccessExample {json} 成功响应:
 *     HTTP/1.1 200 OK
 *     {
            "status": 200,
            "payload": {
                "account": "19942706029",
                "app_sid": "NYL",
                "uuid": "1560505902909725063",
                "username": "逆月翎",
                "comment": "NodeJS后端程序猿",
                "score": 300,
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50IjoiMTk5NDI3MDYwMjkiLCJwYXNzd29yZCI6ImI3NTA4N2ZhNjJhYjJmMmNkZmFiOTA2ZmJiYjQ4ZDVkIiwiYXBwX3NpZCI6Ik5ZTCIsInVzZXJuYW1lIjoi6YCG5pyI57-OIiwiY29tbWVudCI6Ik5vZGVKU-WQjuerr-eoi-W6j-eMvyIsInRpbWUiOjE1NjA1MDU5MDI5MDgsInNpZ24iOiIzZjBlNzJjYzdhZDVmMjMxNzExNGVhZjQ4ZGM2NmFlNSIsInV1aWQiOiIxNTYwNTA1OTAyOTA5NzI1MDYzIiwiaWF0IjoxNTYwNTA1OTAyLCJleHAiOjE1NjA2Nzg3MDIsImlzcyI6Im5peXVlbGluZyJ9.TwyuH5XpJKU10DuQ7n6Hs5BDkrRzdxN9CKNl-qKBEhU",
                "msg": "恭喜，用户注册成功!"
            }
        }
 * @apiSuccess {Number} status 状态码
 * @apiSuccess {Object} payload 返回对象
 * @apiSuccess {String} account 用户账号
 * @apiSuccess {String} app_sid 平台标识
 * @apiSuccess {Object} uuid 用户唯一标识
 * @apiSuccess {Object} username 用户名
 * @apiSuccess {Object} payload
 * 
 * @apiGroup users
 * @apiVersion 1.0.0
 */
router.post('/regist', function (req, res) {
    var par = paramAll(req);

    if (!par.account) {
        return res.json(new ERR('用户账号不为空!', 400));
    }
    if (!par.password) {
        return res.json(new ERR('用户密码不为空!', 400));
    }
    if (!par.app_sid) {
        return res.json(new ERR('平台标识不为空!', 400));
    }
    if (!par.username) {
        return res.json(new ERR('用户名不为空!', 400));
    }
    if (!par.avatar) {
        return res.json(new ERR('头像不为空!', 400));
    }
    if (!par.verifycode) {
        return res.json(new ERR('验证码不为空!', 400));
    }

    //1.加密生成签名sign
    var param = {
        account: par.account,
        password: encryPassword(par.password),
        app_sid: par.app_sid,
        username: par.username,
        avatar: par.avatar,
        uuid: new Date().getTime().toString() + Math.floor(Math.random() * 999999),
        verifycode: par.verifycode,
        type: 0
    };
    if (par.comment) {
        param.comment = par.comment;
    }
    if (par.recommend_code) {
        param.recommend_code = par.recommend_code;
    }

    usersDao.verifyCode(param, function(err, data) {
        if (err) {
            return res.json(new ERR(err, 410));
        } else {
            if (data.status == 200) {
                usersDao.regist(param, function (err, data) {
                    if (err) {
                        return res.json(new ERR(err, 410));
                    } else {
                        if (data.status == 200) {
                            //账号密码匹配生成token与用户信息一起返回给前端
                            data.token = jwt.sign(param, CONFIG.TOKENSECRET, {
                                expiresIn: CONFIG.EXPIRESIN,
                                issuer: CONFIG.ISSUER
                            });
                            return res.json(new PKG({
                                account: param.account,
                                app_sid: param.app_sid,
                                uuid: param.uuid,
                                username: param.username,
                                comment: param.comment,
                                score: 300,
                                token: data.token,
                                avatar: CONFIG.baseImagePath + param.avatar
                            }));
                        } else {
                            return res.json(new ERR(data, 420));
                        }
                    }
                });
            } else {
                return res.json(new ERR(data, 420));
            }
        }
    });
});

function upload_avatar(par, cb) {

    if (!par.avatar) {
        cb('上传头像不能为空!');
    }

    cb(null, 0, par);
}

router.post('/upload_avatar', function (req, res) {
    uploadPicHelper.uploadPicsAndCheckPars(req, upload_avatar, 1, 'upload_avatar', true, function (err, errCode, par) {
        if (err) {
            return res.json(new ERR(err, errCode));
        } 
        
        return res.json(new PKG({
            msg: '头像上传成功!',
            avatar_path: CONFIG.basic_avatar + par.avatar
        }));
    });
});

/**
 * @api {POST} /users/login 用户登录
 * @apiDescription 用户登录接口
 * @apiName userLogin
 * @apiParam {String} account 用户手机号(必填)
 * @apiParam {String} password 用户密码(必填)
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiGroup users
 * @apiVersion 1.0.0
 */
router.post('/login', function (req, res) {
    var par = paramAll(req);

    if (!par.account) {
        return res.json(new ERR('用户账号不为空!', 400));
    }
    if (!par.password) {
        return res.json(new ERR('用户密码不为空!', 400));
    }
    if (!par.app_sid) {
        return res.json(new ERR('平台标识不为空!', 400));
    }

    par.password = encryPassword(par.password)

    usersDao.login(par, function (err, data) {
        if (err) {
            return res.json(new ERR(err, 410));
        } else {
            if (data.status == 200) {
                //账号密码匹配生成token与用户信息一起返回给前端
                data.token = jwt.sign(par, CONFIG.TOKENSECRET, {
                    expiresIn: CONFIG.EXPIRESIN,
                    issuer: CONFIG.ISSUER
                });
                return res.json(new PKG({
                    account: par.account,
                    password: par.password,
                    app_sid: par.app_sid,
                    token: data.token,
                    username: data.userInfo.username,
                    avatar: 'http://pic.niyueling.cn:8000' + data.userInfo.avatar
                }));
            } else {
                return res.json(new ERR(data, 420));
            }
        }
    });
});

/**
 * @api {POST} /users/get_user_score 查询用户积分信息
 * @apiDescription 查询用户积分信息接口
 * @apiName userScore
 * @apiParam {String} account 用户手机号(必填)
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiGroup users
 * @apiVersion 1.0.0
 */
router.post('/get_user_score', function (req, res) {
    var par = paramAll(req);

    //1.加密生成签名sign
    var param = createSign({
        account: par.account,
        app_sid: par.app_sid,
        token: par.token,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if (param.sign == param.sign) {
        //2.签名验证成功，查看token解析账号是否和传参账号一致
        jwt.verify(par.token, CONFIG.TOKENSECRET, (err, data) => {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (par.account == data.account) {
                    //2.token解析数据成功并且账号一致，则查询用户当前积分数据并且返回
                    usersDao.get_user_score(param, function (err, data) {
                        if (err) {
                            return res.json(new ERR(err, 410));
                        } else {
                            if (data.status == 200) {
                                return res.json(new PKG(data));
                            } else {
                                return res.json(new ERR(data, 420));
                            }
                        }
                    });
                } else {
                    return res.json(new ERR('token解析用户数据不匹配!', 420));
                }
            }
        });
    }
});

router.post('/getOpenidInfo', function (req, res) {
    var par = paramAll(req);

    if(!par.code) {
        return res.json(new ERR('参数不全', 410));
    }

    usersDao.getOpenidInfo(par, function (err, data) {
        if (err) {
            return res.json(new ERR(err, 410));
        } 
        
        return res.json(new PKG(data));
    });
});

//获取短信验证码
router.post('/apply_code', function (req, res) {
    var par = paramAll(req);

    if (!par.account || !par.app_sid || !par.type) {
        return res.json(new ERR('参数不全!', 400));
    }

    par.appid = CONFIG.MESSAGE_APP_ID;
    par.appkey = CONFIG.MESSAGE_APP_SECRET;
    par.templateId = 367096;
    par.smsSign = '逆月翎';
    par.smsType = 0;

    var qcloudsms = QcloudSms(par.appid, par.appkey);
    var ssender = qcloudsms.SmsSingleSender();
    par.code = Math.floor(Math.random() * 999999);
    ssender.sendWithParam(86, par.account, par.templateId, [par.code, 30], par.smsSign, "", "", function(err, resp, resData) {
        if(err) {
            return res.json(new ERR(err, 410));
        } else {
            if(resData.errmsg == 'OK') {
                usersDao.saveVerifyCode(par, function(err, data) {
                    if (err) {
                        return res.json(new ERR(err, 410));
                    } else {
                        if (data.status == 200) {
                            return res.json(new PKG(data.msg));
                        } else {
                            return res.json(new ERR(data, 420));
                        }
                    }
                });
            } else {
                return res.json(new ERR(resData.errmsg, 420));
            }
        }
    });
});

router.post('/wx_regist', function (req, res) {
    var par = paramAll(req);

    if (!par.account || !par.avatarUrl|| !par.nickName || !par.openid || !par.verify_code || !par.type) {
        return res.json(new ERR('用户账号不为空!', 400));
    }

    par.password = encryPassword(par.account);
    par.app_sid = 'nyl';
    par.uuid = new Date().getTime().toString() + Math.floor(Math.random() * 999999);

    usersDao.verifyCode(par, function(err, data) {
        if (err) {
            return res.json(new ERR(err, 410));
        } 

        usersDao.wx_regist(par, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } 

            delete par.password;
            
            //账号密码匹配生成token与用户信息一起返回给前端
            par.token = jwt.sign(par, CONFIG.TOKENSECRET, {
                expiresIn: CONFIG.EXPIRESIN,
                issuer: CONFIG.ISSUER
            });
            return res.json(new PKG(par));
        });
    });
});

module.exports = router;